package com.witframework.web.extremetable;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.extremecomponents.table.filter.AbstractExportFilter;
import org.extremecomponents.table.filter.ExportResponseWrapper;

/**
 * 文件导出过滤器，修正了导出时中文文件名为乱码的问题
 * @author wuxinyang
 */
public class ExportFilter extends AbstractExportFilter {
    private boolean responseHeadersSetBeforeDoFilter;

    public void init(FilterConfig filterConfig) throws ServletException {
        String responseHeadersSetBeforeDoFilter = filterConfig.getInitParameter("responseHeadersSetBeforeDoFilter");
        if (StringUtils.isNotBlank(responseHeadersSetBeforeDoFilter)) {
            this.responseHeadersSetBeforeDoFilter = new Boolean(responseHeadersSetBeforeDoFilter).booleanValue();
        }
    }
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain, String exportFileName) throws IOException, ServletException {
    	//fuck 靠bug
    	//导出时中文文件名为乱码的问题解决
    	String encoding=request.getCharacterEncoding();
    	if(encoding.equalsIgnoreCase("GBK")){
    		exportFileName =new String(exportFileName.getBytes("GBK"),"iso-8859-1");
    	}else if(encoding.equalsIgnoreCase("GB2312")){
    		exportFileName =new String(exportFileName.getBytes("GB2312"),"iso-8859-1");
    	}else if(encoding.equalsIgnoreCase("utf-8")){
    		exportFileName =new String(exportFileName.getBytes("GB2312"),"iso-8859-1");
    	}    	
    	if (responseHeadersSetBeforeDoFilter) {
            setResponseHeaders((HttpServletResponse) response, exportFileName);
        }
        chain.doFilter(request, new ExportResponseWrapper((HttpServletResponse) response));
        if (!responseHeadersSetBeforeDoFilter) {
            setResponseHeaders((HttpServletResponse) response, exportFileName);
        }        
    }
	public void destroy() {		
		
	}
}
